// 函数组件
import React, { useEffect, useState } from 'react';
import './css/AuthorityManagement.less'
import { Button, Modal, Form, Input, Switch, Select,Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import AddManagement from './child/AddManagement';
import EditAddManagement from './child/EditAddManagement';
import { getMember, delEmpls, updataState, getRoleNames } from '../../../api/authority';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import getSelectTime from '../../../utils/date'
interface DataType {
    key: React.Key;
    id: number;
    user: string;
    name: string;
    eMail: string;
    num: string;
    role: string;
    loginTime: string;
    isGo: number;
}

interface rolesType {
    emplId: number,
    emplMail: string,
    emplName: string,
    emplNumber: string,
    emplPhone: string,
    lastTime: string,
    roleName: string,
    state: number
}

interface menuType {
    menuId: number,
    des: string,
    menuName: string,
    menuRemark: string,
    menuUrl: null,
    pid: number,
    icon: null
}

function AuthorityManagement() {
    const [isAdd, setIsAdd] = useState<boolean>(false)
    const [isEdit, setIsEdit] = useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [editValue, setEditValue] = useState<DataType | null>(null)  //点击的哪一行数据
    const [findInput, setFindInput] = useState<string>() //input 值
    const [findSelected, setFindSelected] = useState<string>() //多选框值
    const [rolesList, setRolesList] = useState<rolesType[]>([]) //装渲染成员信息
    // const [menuList, setMenuList] = useState<menuType[]>([]) //装权限菜单
    const [roleNamesList, setRoleNamesList] = useState<string[]>([]) //装角色列表
    const [form] = Form.useForm();
    useEffect(() => {
        showRoles()
    }, [])

    const showRoles = () => {
        getMember({ keys: '', roleName: '' }).then(res => {
            console.log('所有信息', res);
            let newRoles = res.data.map(function (item: rolesType) {
                item.lastTime = getSelectTime(item.lastTime)
                return item
            })
            // console.log(newRoles);
            // dayjs.extend(utc)
            setRolesList(newRoles)
            // console.log("time", dayjs.utc(new Date()).format())
            // setRolesList(newRoles)
        }).catch(err => {
            console.log('所有信息', err);
        })

        getRoleNames().then(res => {
            console.log('所有信息', res);
            setRoleNamesList(res.data)
        }).catch(err => {
            console.log('所有信息', err);
        })
    }

    const start = () => {
        setLoading(true);
        // ajax request after empty completing
        setTimeout(() => {
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    };
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const onChange = (checked: boolean) => {
        console.log(`switch to ${checked}`);
    };
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
            width: '8%',
            align: 'center'
        },
        {
            title: '成员账号',
            dataIndex: 'user',
            width: '15%',
            align: 'center'
        },
        {
            title: '姓名',
            dataIndex: 'name',
            width: '10%',
            align: 'center'
        },
        {
            title: '手机号',
            dataIndex: 'num',
            width: '12%',
            align: 'center'
        },
        {
            title: '邮箱',
            dataIndex: 'eMail',
            width: '16%',
            align: 'center'
        },
        {
            title: '角色',
            dataIndex: 'role',
            width: '10%',
            align: 'center'
        },
        {
            title: '最近登录时间',
            dataIndex: 'loginTime',
            width: '11%',
            align: 'center'
        },
        {
            title: '是否启用',
            dataIndex: 'isGo',
            width: '10%',
            align: 'center',
            render: (_, record) => (
                <div>
                    <Switch defaultChecked={record.isGo == 1 ? true : false} onChange={onChange} />
                </div>
            ),
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '20%',
            align: 'center',
            render: (_, record) => (
                <div>
                    <button className='edit' onClick={() => openEdit(record)}>编辑</button>
                    <button className='del'  onClick={() => del(record)}>删除</button>
                </div>
            ),
        },
    ];

    const data: DataType[] = [];
    for (let i = 0; i < rolesList.length; i++) {
        data.push({
            key: i,
            id: rolesList[i].emplId,
            user: rolesList[i].emplNumber,
            name: rolesList[i].emplName,
            eMail: rolesList[i].emplMail,
            num: rolesList[i].emplPhone,
            role: rolesList[i].roleName,
            loginTime: rolesList[i].lastTime,
            isGo: rolesList[i].state
        });
    }

    //批量删除
    const BatchDeletion = () => {
        console.log('批量删除');
        console.log(selectedRowKeys);
        let delList: any = []
        rolesList.forEach(function (item, index) {
            selectedRowKeys.forEach(function (item2) {
                if (index == item2) {
                    delList.push(item.emplId)
                }
            })
        })
        // selectedRowKeys.forEach(function(item){
        //     delList.push(item)
        // })
        console.log(delList);

        delEmpls(delList).then(res => {
            console.log('所有信息', res);
            showRoles()
        }).catch(err => {
            console.log('所有信息', err);
        })
    }
    const { confirm } = Modal
    const del = (item: DataType) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '是否删除该角色',
            onOk() {
                console.log('OK');
                console.log(item.id);
                let delList = []
                delList.push(item.id)
                console.log(delList);
                delEmpls(delList).then(res => {
                    console.log('所有信息', res);
                    showRoles()
                }).catch(err => {
                    console.log('所有信息', err);
                })
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    //添加
    const addRole = () => {
        setIsAdd(true)
    }
    const closeAdd = () => {
        setIsAdd(false)
    }

    //编辑
    const openEdit = (item: DataType): void => {
        setIsEdit(true)
        setEditValue(item)
        console.log(1);

    }

    const closeEdit = () => {
        setIsEdit(false)
    }
    //重启
    const restart = ()=>{
        form.resetFields();
        setFindInput('')
        showRoles()
    }
    //查找
    const find = () => {
        console.log(findInput, findSelected);
        getMember({ keys: findInput, roleName: findSelected }).then(res => {
            console.log('所有信息', res);
            let newRoles = res.data.map(function (item: rolesType) {
                item.lastTime = getSelectTime(item.lastTime)
                return item
            })
            // console.log(newRoles);
            // dayjs.extend(utc)
            setRolesList(newRoles)
            // console.log("time", dayjs.utc(new Date()).format())
            // setRolesList(newRoles)
        }).catch(err => {
            console.log('所有信息', err);
        })
        form.resetFields();
    }
    //input框输入值赋值
    const changeFind = (e: any) => {
        // console.log(e.target.value);
        setFindInput(e.target.value)
    }
    //多选框赋值
    const handleChange = (value: string) => {
        console.log(`selected ${value}`);
        setFindSelected(value)
    };
    const onFinish = (values: any) => {
        
    }
    return (
        <div className='AuthorityManagement'>
            {/* 头部 */}
            <div className='page-top'>
                {/* 左边标题 */}
                <div className='page-title'>
                    <p>成员管理</p>
                </div>
            </div>
            {/* 内容区 */}
            <div className='page-context'>
                {/* 筛选卡片 */}
                <div className='screening-card'>
                    <div className='screening'>
                        <p>筛选查询</p>
                    </div>
                    <Form
                    name="basic"
                    form={form}
                   
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}

                    autoComplete="off"
                >
                    <Form.Item
                        label="角色"
                        name="roles"
                    >
                        <Input placeholder="成员账号/姓名"
                            // value={findInput}
                            onChange={changeFind}></Input>
                    </Form.Item>
                    <Form.Item
                        label="关键词"
                        name="username"
                    >
                        <Select
                            
                            style={{ width: 120 }}
                            onChange={handleChange}
                            options={roleNamesList.map(item => ({
                                value: item,
                                label: item,
                              }))}
                            //   onClear={onClear}
                        />
                    </Form.Item>

                    
                </Form>
                <div className='twoButton'>
                        <button className='reset' onClick={restart}>重置</button>
                        <button className='filter' onClick={find}>筛选</button>
                    </div>
                </div>
                {/* 数据表部分 */}
                <div className='data-list'>
                    {/* 上部文字 */}
                    <div className='list-text'>
                        <p>数据列表</p>
                        <div>
                            <button className='batch-del' onClick={BatchDeletion}>批量删除</button>
                            <button className='add' onClick={addRole}>添加</button>
                        </div>
                    </div>
                    {/* 数据 */}
                    <div>
                        <ConfigProvider locale={zh_CN}>
                            <Table
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={data}
                                scroll={{ y: 290 }}
                                pagination={{
                                    position: ['bottomCenter'],
                                    defaultPageSize: 3,
                                    pageSizeOptions: [3, 5, 10, 15],
                                    showQuickJumper: true,
                                    showSizeChanger: true
                                }}
                                bordered
                            />
                        </ConfigProvider>
                    </div>
                    <EditAddManagement isEdit={isEdit} closeEdit={closeEdit} editValue={editValue} roleNamesList={roleNamesList} showRoles={showRoles}></EditAddManagement>
                    <AddManagement isAdd={isAdd} closeAdd={closeAdd} roleNamesList={roleNamesList}  showRoles={showRoles}></AddManagement>
                </div>
            </div>

        </div>
    )
}

export default AuthorityManagement